package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.rpc.domain.AnalysisManageRightRoleAdminRelDTO;
import com.hunttown.mes.rpc.domain.AnalysisManageRightRoleMenuRelDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisManageRightRoleMenuRelDTOQuery;
import com.hunttown.mes.rpc.api.AnalysisManageRightRoleRpcService;
import com.hunttown.mes.rpc.domain.AnalysisManageRightRoleDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisManageRightRoleAdminRelDTOQuery;
import com.hunttown.mes.rpc.domain.query.AnalysisManageRightRoleDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * created by hunttown on 2018-10-26 15:04:56
 */
@Service
public class AnalysisManageRightRoleManageService {

    private final static Logger logger = LoggerFactory.getLogger(AnalysisManageRightRoleManageService.class);

    private final AnalysisManageRightRoleRpcService rpcService;
    private final AnalysisManageRightRoleAdminRelManageService roleAdminRelService;
    private final AnalysisManageRightRoleMenuRelManageService roleMenuRelService;

    @Autowired
    public AnalysisManageRightRoleManageService(AnalysisManageRightRoleRpcService rpcService, AnalysisManageRightRoleAdminRelManageService roleAdminRelService, AnalysisManageRightRoleMenuRelManageService roleMenuRelService) {
        this.rpcService = rpcService;
        this.roleAdminRelService = roleAdminRelService;
        this.roleMenuRelService = roleMenuRelService;
    }

    // 新增
    public AnalysisManageRightRoleDTO insert(AnalysisManageRightRoleDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(AnalysisManageRightRoleDTO objDTO) {
        return rpcService.updateInfoById(objDTO);
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(AnalysisManageRightRoleDTOQuery objDTOQuery) {
        return rpcService.updateInfoByQuery(objDTOQuery);
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        return rpcService.deleteById(id);
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        AnalysisManageRightRoleDTOQuery query = new AnalysisManageRightRoleDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        return rpcService.updateInfoByQuery(query);
    }

    // 通过ID获取
    public AnalysisManageRightRoleDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public AnalysisManageRightRoleDTO getByQuery(AnalysisManageRightRoleDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<AnalysisManageRightRoleDTO> getForPage(AnalysisManageRightRoleDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        AnalysisManageRightRoleDTO obj = new AnalysisManageRightRoleDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    /**
     * 根据用户Id获取角色ID列表
     *
     * @param id 用户Id
     * @return 角色ID列表
     */
    public List<Integer> getRoleIdListByManageId(Integer id) {
        List<Integer> list = new ArrayList<>();

        AnalysisManageRightRoleAdminRelDTOQuery query = new AnalysisManageRightRoleAdminRelDTOQuery();
        query.setPageSize(10000);
        query.setAdminId(id);
        Page<AnalysisManageRightRoleAdminRelDTO> page = roleAdminRelService.getForPage(query);

        if (page.getItems().size() > 0) {
            page.getItems().forEach(s -> list.add(s.getRoleId()));
        }

        return list;
    }

    /**
     * 根据角色Id获取权限菜单ID列表
     *
     * @param id 角色Id
     * @return 权限菜单ID列表
     */
    public List<Integer> getMenuIdListByRoleId(Integer id) {
        List<Integer> list = new ArrayList<>();

        AnalysisManageRightRoleMenuRelDTOQuery query = new AnalysisManageRightRoleMenuRelDTOQuery();
        query.setPageSize(10000);
        query.setRoleId(id);
        Page<AnalysisManageRightRoleMenuRelDTO> page = roleMenuRelService.getForPage(query);

        if (page.getItems().size() > 0) {
            page.getItems().forEach(s -> list.add(s.getMenuId()));
        }

        return list;
    }

    /**
     * 根据id 获取角色名称
     *
     * @param id 角色ID
     * @return 角色名称
     */
    public String getRoleNameById(Integer id) {
        String roleName = "";

        if (id > 0) {
            AnalysisManageRightRoleDTO obj = getById(id);
            if (obj != null) {
                roleName = obj.getRoleName();
            }
        }

        return roleName;
    }

    /**
     * 通过唯一代码获取记录
     *
     * @param roleCode 角色代码
     * @return 角色
     */
    public AnalysisManageRightRoleDTO getByRoleCode(String roleCode) {
        AnalysisManageRightRoleDTOQuery rightRoleDTOQuery = new AnalysisManageRightRoleDTOQuery();
        rightRoleDTOQuery.setRoleNameEn(roleCode);
        List<AnalysisManageRightRoleDTO> list = rpcService.getListForPage(rightRoleDTOQuery).getItems();

        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 通过角色英文名称和管理员Id获取此管理是否有此权限
     *
     * @param roleCode 角色英文名称
     * @param adminId  管理员Id
     * @return 0无权限 大于0有权限
     */
    public Integer getRoleAdminRel(String roleCode, Integer adminId) {
        Integer id = 0;

        AnalysisManageRightRoleDTO dto = getByRoleCode(roleCode);
        if (dto == null) {
            return id;
        }

        AnalysisManageRightRoleAdminRelDTO relDTO = roleAdminRelService.getByAdminRole(adminId, dto.getId());
        if (relDTO == null) {
            return id;
        }

        id = relDTO.getId();

        return id;
    }

    /**
     * 构建左侧分类树 A2-1
     *
     * @param menuType 0基础菜单，1checkbox菜单
     * @param adminId  角色ID
     * @param isSuper  是否是管理员，管理员才显示自定义的管理权限
     * @return 菜单
     */
    public List<String> createCateTree(Integer menuType, Integer adminId, Integer isSuper) {
        //取出 Role 列表
        AnalysisManageRightRoleDTOQuery manageRightRoleDTOQuery = new AnalysisManageRightRoleDTOQuery();
        if (isSuper == 0) {
            manageRightRoleDTOQuery.setIsSuperRole(0);
        }
        manageRightRoleDTOQuery.setPageSize(10000);
        manageRightRoleDTOQuery.setStopFlag(0);
        List<AnalysisManageRightRoleDTO> list = rpcService.getListForPage(manageRightRoleDTOQuery).getItems();

        List<Integer> roleList = new ArrayList<>();
        if (menuType == 1 && adminId > 0) {
            //取出用户角色关系
            AnalysisManageRightRoleAdminRelDTOQuery query = new AnalysisManageRightRoleAdminRelDTOQuery();
            query.setPageSize(10000);
            query.setAdminId(adminId);

            roleAdminRelService.getForPage(query).getItems().forEach(s -> roleList.add(s.getRoleId()));
        }

        return getList(list, 0, roleList, menuType);
    }

    /**
     * 递归 A2-2
     *
     * @param mainList 菜单
     * @param parentId 父ID
     * @param roleList 角色
     * @param menuType 0基础菜单，1checkbox菜单
     * @return 菜单
     */
    private List<String> getList(List<AnalysisManageRightRoleDTO> mainList, Integer parentId, List<Integer> roleList, Integer menuType) {

        List<String> result = new ArrayList<>();

        if (mainList == null || mainList.size() == 0) {
            return result;
        }

        List<AnalysisManageRightRoleDTO> filterList = mainList.stream().filter(s -> s.getParentId().equals(parentId)).collect(Collectors.toList());

        if (filterList.size() == 0) {
            return result;
        }

        // 启用停用标识
        String stopFlag = "";
        // 菜单选中标识
        String chkSign = "";

        result.add("<ul>");
        for (AnalysisManageRightRoleDTO item : filterList) {
            if (item.getStopFlag().equals(1)) {
                stopFlag = "（停用）";
            } else {
                stopFlag = "";
            }

            if (menuType == 1) {
                if (roleList != null && roleList.size() > 0) {
                    if (roleList.contains(item.getId())) {
                        chkSign = ", \"selected\":true";
                    } else {
                        chkSign = "";
                    }
                }
            }

            result.add("<li data-jstree='{\"opened\":true " + chkSign + "}' roleId='" + item.getId() + "'><a href='javascript:void(0);' onclick='roleEditUrl(" + item.getId() + ", " + item.getParentId() + ")'>" + item.getRoleName() + stopFlag + "</a>");

            //递归
            List<String> list = getList(mainList, item.getId(), roleList, menuType);
            for (String child : list) {
                result.add(child);
            }

            result.add("</li>");
        }
        result.add("</ul>");

        return result;
    }


    //region 取出当前分类及及子类

    /**
     * 取出每条记录的子类，一并返回
     *
     * @param list 菜单
     * @return 菜单列表
     */
    public List<AnalysisManageRightRoleDTO> getChildrenForEach(List<AnalysisManageRightRoleDTO> list, String mark) {
        if (list == null || list.size() == 0) {
            return list;
        }

        List<AnalysisManageRightRoleDTO> return_list = new ArrayList<>();
        List<AnalysisManageRightRoleDTO> child_list = new ArrayList<>();

        for (AnalysisManageRightRoleDTO item : list) {
            child_list = getChildrenById(item, mark);
            return_list.addAll(child_list);
        }

        return return_list;
    }

    /**
     * 取出每条记录的子类，一并返回（具体实施）
     *
     * @param dto 角色
     * @return 菜单列表
     */
    public List<AnalysisManageRightRoleDTO> getChildrenById(AnalysisManageRightRoleDTO dto, String mark) {
        List<AnalysisManageRightRoleDTO> child_list = new ArrayList<>();
        child_list.add(dto);

        if (mark.equals("|")) {
            mark += "┄";
        } else {
            mark += " ┄";
        }

        AnalysisManageRightRoleDTOQuery query = new AnalysisManageRightRoleDTOQuery();
        query.setParentId(dto.getId());
        query.setStopFlag(0);
        query.setPageSize(10000);
        Page<AnalysisManageRightRoleDTO> dataPage = getForPage(query);

        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (AnalysisManageRightRoleDTO item : dataPage.getItems()) {
                item.setRoleName(mark + " " + item.getRoleName());
                List<AnalysisManageRightRoleDTO> next_list = getChildrenById(item, mark);
                child_list.addAll(next_list);
            }
        }

        return child_list;
    }
    //endregion

}